<?php


class tlwangguan
{
    function submit()
    {
//        print_r($_POST);
        $orderInfo = Model()->table('order')->where([
            'pay_sn' => $_POST['pay_sn']
        ])->find();
        if (!$orderInfo) {
            showMessage("订单不存在！", '/shop/index.php?act=member_order&op=index', 'html', 'error');
            exit;
        }
//        print_r($orderInfo);
        if ($orderInfo['order_state'] != 10) {
            showMessage("订单不可支付！", '/shop/index.php?act=member_order&op=index', 'html', 'error');
            exit;
        }
        $payment = Model()->table('payment')->where([
            'payment_code' => 'tlwangguan'
        ])->find();
        $pconfig = unserialize($payment['payment_config']);
		
		$ogoods = Model()->table("order_goods")->where([
			'order_id' => $orderInfo['order_id']
		])->select();
		

//        set_include_path(get_include_path() . PATH_SEPARATOR . 'phpseclib');
        require("phpseclib/File/X509.php");
        require("phpseclib/Crypt/RSA.php");

//如果不用证书加密，使用php_rsa.php函数
        require_once("php_rsa.php");

        $_POST['version'] = 'v1.0';
        $_POST['inputCharset'] = '1';
        $_POST['signType'] = '1';
        $_POST['payType'] = '0';
        $_POST['tradeNature'] = 'GOODS';
        $_POST["key"] = $pconfig['signkey'];
        $_POST['orderNo'] = $orderInfo['order_sn'];
        $_POST['orderAmount'] = (int)($orderInfo['order_amount'] * 100);
        $_POST['orderDatetime'] = date("YmdHis");
        $_POST['merchantId'] = $pconfig['merchant_code'];
		$_POST['productName'] = $ogoods[0]['goods_name'];
		$_POST['productPrice'] = $ogoods[0]['goods_price'];
		$_POST['productNum'] = $ogoods[0]['goods_num'];
		$_POST['payerName'] = $orderInfo['receiver_name'];
		
		$_POST['customsExt'] = "<GW_CUSTOMS><CUSTOMS_TYPE>HG019</CUSTOMS_TYPE><ESHOP_ENT_CODE>{$pconfig['beian_code']}</ESHOP_ENT_CODE><ESHOP_ENT_NAME>{$pconfig['beian_name']}</ESHOP_ENT_NAME><BIZ_TYPE_CODE>CQ</BIZ_TYPE_CODE><PAYER_NAME>{$orderInfo['receiver_name']}</PAYER_NAME><PAPER_TYPE>01</PAPER_TYPE><PAPER_NUMBER>${orderInfo['idcard']}</PAPER_NUMBER><NOTE></NOTE></GW_CUSTOMS>";
		
		// "<GW_CUSTOMS><CUSTOMS_TYPE>HG019</CUSTOMS_TYPE><EShop_ENT_CODE>4403160W4T</EShop_ENT_CODE><EShop_ENT_NAME>深圳市创久鸿贸易有限公司</EShop_ENT_NAME><BIZ_TYPE_CODE>CQ</BIZ_TYPE_CODE><PAYER_NAME>".$orderInfo['receiver_name']."</PAYER_NAME><PAPER_TYPE>01</PAPER_TYPE><PAPER_NUMBER>".$orderInfo['idcard']."</PAPER_NUMBER><NOTE></NOTE></GW_CUSTOMS>";
		
        $_POST['pickupUrl'] = SHOP_SITE_URL . "/api/payment/tlwangguan/return_url.php";
        $_POST['receiveUrl'] = SHOP_SITE_URL . "/api/payment/tlwangguan/notify_url.php";

//页面编码要与参数inputCharset一致，否则服务器收到参数值中的汉字为乱码而导致验证签名失败。
        $serverUrl = $_POST["serverUrl"];
        $inputCharset = $_POST["inputCharset"];
        $pickupUrl = $_POST["pickupUrl"];
        $receiveUrl = $_POST["receiveUrl"];
        $version = $_POST["version"];
        $language = $_POST["language"];
        $signType = $_POST["signType"];
        $merchantId = $_POST["merchantId"];
        $payerName = $_POST["payerName"];
        $payerEmail = $_POST["payerEmail"];
        $payerTelephone = $_POST["payerTelephone"];
        $payerIDCard = $_POST["payerIDCard"];
        $pid = $_POST["pid"];
        $orderNo = $_POST["orderNo"];
        $orderAmount = $_POST["orderAmount"];
        $orderDatetime = $_POST["orderDatetime"];
        $orderCurrency = $_POST["orderCurrency"];
        $orderExpireDatetime = $_POST["orderExpireDatetime"];
        $productName = $_POST["productName"];
        $productId = $_POST["productId"];
        $productPrice = $_POST["productPrice"];
        $productNum = $_POST["productNum"];
        $productDesc = $_POST["productDesc"];
        $ext1 = $_POST["ext1"];
        $ext2 = $_POST["ext2"];
        $extTL = $_POST["extTL"];
        $payType = $_POST["payType"]; //payType   不能为空，必须放在表单中提交。
        $issuerId = $_POST["issuerId"]; //issueId 直联时不为空，必须放在表单中提交。
        $pan = $_POST["pan"];
        $tradeNature = $_POST["tradeNature"];
        $customsExt = $_POST["customsExt"];
        $key = $_POST["key"];


//报文参数有消息校验
//if(preg_match("/\d/",$pickupUrl)){
//echo "<script>alert('pickupUrl有误！！');history.back();</script>";
//}

// 生成签名字符串。
        $bufSignSrc = "";
        if ($inputCharset != "")
            $bufSignSrc = $bufSignSrc . "inputCharset=" . $inputCharset . "&";
        if ($pickupUrl != "")
            $bufSignSrc = $bufSignSrc . "pickupUrl=" . $pickupUrl . "&";
        if ($receiveUrl != "")
            $bufSignSrc = $bufSignSrc . "receiveUrl=" . $receiveUrl . "&";
        if ($version != "")
            $bufSignSrc = $bufSignSrc . "version=" . $version . "&";
        if ($language != "")
            $bufSignSrc = $bufSignSrc . "language=" . $language . "&";
        if ($signType != "")
            $bufSignSrc = $bufSignSrc . "signType=" . $signType . "&";
        if ($merchantId != "")
            $bufSignSrc = $bufSignSrc . "merchantId=" . $merchantId . "&";
        if ($payerName != "")
            $bufSignSrc = $bufSignSrc . "payerName=" . $payerName . "&";
        if ($payerEmail != "")
            $bufSignSrc = $bufSignSrc . "payerEmail=" . $payerEmail . "&";
        if ($payerTelephone != "")
            $bufSignSrc = $bufSignSrc . "payerTelephone=" . $payerTelephone . "&";

//需要加密付款人身份证信息
        if ($payerIDCard != "") {
            /*
            //测身份证信息认证使用商户号：20150513442
            //加密函数从php_rsa.php 调用


            $publickeyfile = './publickey.txt';
            $publickeycontent = file_get_contents($publickeyfile);

            $publickeyarray = explode(PHP_EOL, $publickeycontent);
            $publickey_arr = explode('=',$publickeyarray[0]);
            $modulus_arr = explode('=',$publickeyarray[1]);
            $publickey = trim($publickey_arr[1]);
            $modulus = trim($modulus_arr[1]);
            $keylength = 1024;
            $ciphertext = base64_encode(rsa_encrypt($payerIDCard, $publickey, $modulus, $keylength));
            */


            //测身份证信息认证使用商户号：20150513442
            //加密函数从phpseclib调用
            $certfile = file_get_contents('TLCert-test.cer');
            $x509 = new File_X509();
            $cert = $x509->loadX509($certfile);
            $pubkey = $x509->getPublicKey();

            $rsa = new Crypt_RSA();
            $rsa->loadKey($pubkey);
            $rsa->setPublicKey();
            $rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
            $ciphertext = $rsa->encrypt($payerIDCard);
            $ciphertext = base64_encode($ciphertext);


            $payerIDCard = $ciphertext;
            $bufSignSrc = $bufSignSrc . "payerIDCard=" . $payerIDCard . "&";

        }

        if ($pid != "")
            $bufSignSrc = $bufSignSrc . "pid=" . $pid . "&";
        if ($orderNo != "")
            $bufSignSrc = $bufSignSrc . "orderNo=" . $orderNo . "&";
        if ($orderAmount != "")
            $bufSignSrc = $bufSignSrc . "orderAmount=" . $orderAmount . "&";
        if ($orderCurrency != "")
            $bufSignSrc = $bufSignSrc . "orderCurrency=" . $orderCurrency . "&";
        if ($orderDatetime != "")
            $bufSignSrc = $bufSignSrc . "orderDatetime=" . $orderDatetime . "&";
        if ($orderExpireDatetime != "")
            $bufSignSrc = $bufSignSrc . "orderExpireDatetime=" . $orderExpireDatetime . "&";
        if ($productName != "")
            $bufSignSrc = $bufSignSrc . "productName=" . $productName . "&";
        if ($productPrice != "")
            $bufSignSrc = $bufSignSrc . "productPrice=" . $productPrice . "&";
        if ($productNum != "")
            $bufSignSrc = $bufSignSrc . "productNum=" . $productNum . "&";
        if ($productId != "")
            $bufSignSrc = $bufSignSrc . "productId=" . $productId . "&";
        if ($productDesc != "")
            $bufSignSrc = $bufSignSrc . "productDesc=" . $productDesc . "&";
        if ($ext1 != "")
            $bufSignSrc = $bufSignSrc . "ext1=" . $ext1 . "&";

//如果海关扩展字段不为空，需要做个MD5填写到ext2里
        if ($ext2 == "" && $customsExt != "") {
            $ext2 = strtoupper(md5($customsExt));
            $bufSignSrc = $bufSignSrc . "ext2=" . $ext2 . "&";
        } else if ($ext2 != "") {
            $bufSignSrc = $bufSignSrc . "ext2=" . $ext2 . "&";
        }

        if ($extTL != "")
            $bufSignSrc = $bufSignSrc . "extTL" . $extTL . "&";
        if ($payType != "")
            $bufSignSrc = $bufSignSrc . "payType=" . $payType . "&";
        if ($issuerId != "")
            $bufSignSrc = $bufSignSrc . "issuerId=" . $issuerId . "&";
        if ($pan != "")
            $bufSignSrc = $bufSignSrc . "pan=" . $pan . "&";
        if ($tradeNature != "")
            $bufSignSrc = $bufSignSrc . "tradeNature=" . $tradeNature . "&";
        $bufSignSrc = $bufSignSrc . "key=" . $key; //key为MD5密钥，密钥是在通联支付网关商户服务网站上设置。

//签名，设为signMsg字段值。
        $signMsg = strtoupper(md5($bufSignSrc));
        ?>
        <form name="form2" action="<?php echo $pconfig['address'] ?>" method="post" id="form">
            <input type="hidden" name="inputCharset" id="inputCharset" value="<?php echo $inputCharset ?>"/>
            <input type="hidden" name="pickupUrl" id="pickupUrl" value="<?php echo $pickupUrl ?>"/>
            <input type="hidden" name="receiveUrl" id="receiveUrl" value="<?php echo $receiveUrl ?>"/>
            <input type="hidden" name="version" id="version" value="<?php echo $version ?>"/>
            <input type="hidden" name="language" id="language" value="<?php echo $language ?>"/>
            <input type="hidden" name="signType" id="signType" value="<?php echo $signType ?>"/>
            <input type="hidden" name="merchantId" id="merchantId" value="<?php echo $merchantId ?>"/>
            <input type="hidden" name="payerName" id="payerName" value="<?php echo $payerName ?>"/>
            <input type="hidden" name="payerEmail" id="payerEmail" value="<?php echo $payerEmail ?>"/>
            <input type="hidden" name="payerTelephone" id="payerTelephone" value="<?php echo $payerTelephone ?>"/>
            <input type="hidden" name="payerIDCard" id="payerIDCard" value="<?php echo $payerIDCard ?>"/>
            <input type="hidden" name="pid" id="pid" value="<?php echo $pid ?>"/>
            <input type="hidden" name="orderNo" id="orderNo" value="<?php echo $orderNo ?>"/>
            <input type="hidden" name="orderAmount" id="orderAmount" value="<?php echo $orderAmount ?>"/>
            <input type="hidden" name="orderCurrency" id="orderCurrency" value="<?php echo $orderCurrency ?>"/>
            <input type="hidden" name="orderDatetime" id="orderDatetime" value="<?php echo $orderDatetime ?>"/>
            <input type="hidden" name="orderExpireDatetime" id="orderExpireDatetime"
                   value="<?php echo $orderExpireDatetime ?>"/>
            <input type="hidden" name="productName" id="productName" value="<?php echo $productName ?>"/>
            <input type="hidden" name="productPrice" id="productPrice" value="<?php echo $productPrice ?>"/>
            <input type="hidden" name="productNum" id="productNum" value="<?php echo $productNum ?>"/>
            <input type="hidden" name="productId" id="productId" value="<?php echo $productId ?>"/>
            <input type="hidden" name="productDesc" id="productDesc" value="<?php echo $productDesc ?>"/>
            <input type="hidden" name="ext1" id="ext1" value="<?php echo $ext1 ?>"/>
            <input type="hidden" name="ext2" id="ext2" value="<?php echo $ext2 ?>"/>
            <input type="hidden" name="extTL" id="extTL" value="<?php echo $extTL ?>"/>
            <input type="hidden" name="payType" value="<?php echo $payType ?>"/>
            <input type="hidden" name="issuerId" value="<?php echo $issuerId ?>"/>
            <input type="hidden" name="pan" value="<?php echo $pan ?>"/>
            <input type="hidden" name="tradeNature" value="<?php echo $tradeNature ?>"/>
            <input type="hidden" name="customsExt" value="<?php echo $customsExt ?>"/>
            <input type="hidden" name="signMsg" id="signMsg" value="<?php echo $signMsg ?>"/>
            <div align="center">
                <!--                <input type="submit" value="确认付款，到通联支付去啦" align=center/>-->
            </div>
            <!--================= post 方式提交支付请求 end =====================-->
        </form>
        <script>
            document.getElementById('form').submit();
        </script>
        <?php
        exit;
    }


    function notify_verify()
    {
        require("phpseclib/File/X509.php");
        require("phpseclib/Crypt/RSA.php");

//如果不用证书加密，使用php_rsa.php函数
        require_once("php_rsa.php");

//测试商户的key! 请修改。
        $payment = Model()->table('payment')->where([
            'payment_code' => 'tlwangguan'
        ])->find();
        $pconfig = unserialize($payment['payment_config']);
        $md5key = $pconfig['signkey'];

        $merchantId = $_POST["merchantId"];
        $version = $_POST['version'];
        $language = $_POST['language'];
        $signType = $_POST['signType'];
        $payType = $_POST['payType'];
        $issuerId = $_POST['issuerId'];
        $paymentOrderId = $_POST['paymentOrderId'];
        $orderNo = $_POST['orderNo'];
        $orderDatetime = $_POST['orderDatetime'];
        $orderAmount = $_POST['orderAmount'];
        $payDatetime = $_POST['payDatetime'];
        $payAmount = $_POST['payAmount'];
        $ext1 = $_POST['ext1'];
        $ext2 = $_POST['ext2'];
        $payResult = $_POST['payResult'];
        $errorCode = $_POST['errorCode'];
        $returnDatetime = $_POST['returnDatetime'];
        $signMsg = $_POST["signMsg"];

//var_dump($_POST);


        $bufSignSrc = "";
        if ($merchantId != "")
            $bufSignSrc = $bufSignSrc . "merchantId=" . $merchantId . "&";
        if ($version != "")
            $bufSignSrc = $bufSignSrc . "version=" . $version . "&";
        if ($language != "")
            $bufSignSrc = $bufSignSrc . "language=" . $language . "&";
        if ($signType != "")
            $bufSignSrc = $bufSignSrc . "signType=" . $signType . "&";
        if ($payType != "")
            $bufSignSrc = $bufSignSrc . "payType=" . $payType . "&";
        if ($issuerId != "")
            $bufSignSrc = $bufSignSrc . "issuerId=" . $issuerId . "&";
        if ($paymentOrderId != "")
            $bufSignSrc = $bufSignSrc . "paymentOrderId=" . $paymentOrderId . "&";
        if ($orderNo != "")
            $bufSignSrc = $bufSignSrc . "orderNo=" . $orderNo . "&";
        if ($orderDatetime != "")
            $bufSignSrc = $bufSignSrc . "orderDatetime=" . $orderDatetime . "&";
        if ($orderAmount != "")
            $bufSignSrc = $bufSignSrc . "orderAmount=" . $orderAmount . "&";
        if ($payDatetime != "")
            $bufSignSrc = $bufSignSrc . "payDatetime=" . $payDatetime . "&";
        if ($payAmount != "")
            $bufSignSrc = $bufSignSrc . "payAmount=" . $payAmount . "&";
        if ($ext1 != "")
            $bufSignSrc = $bufSignSrc . "ext1=" . $ext1 . "&";
        if ($ext2 != "")
            $bufSignSrc = $bufSignSrc . "ext2=" . $ext2 . "&";
        if ($payResult != "")
            $bufSignSrc = $bufSignSrc . "payResult=" . $payResult . "&";
        if ($errorCode != "")
            $bufSignSrc = $bufSignSrc . "errorCode=" . $errorCode . "&";
        if ($returnDatetime != "")
            $bufSignSrc = $bufSignSrc . "returnDatetime=" . $returnDatetime;

//验签
        if ($signType == '1') {
            /*
            //解析publickey.txt文本获取公钥信息

            $publickeyfile = './publickey.txt';
            $publickeycontent = file_get_contents($publickeyfile);

            $publickeyarray = explode(PHP_EOL, $publickeycontent);
            $publickey_arr = explode('=',$publickeyarray[0]);
            $modulus_arr = explode('=',$publickeyarray[1]);
            $publickey = trim($publickey_arr[1]);
            $modulus = trim($modulus_arr[1]);



            $keylength = 1024;
            //验签结果
            $verifyResult = rsa_verify($bufSignSrc,$signMsg, $publickey, $modulus, $keylength,"sha1");
            */


            //解析证书方式
            $certfile = file_get_contents('TLCert-test.cer');
            $x509 = new File_X509();
            $cert = $x509->loadX509($certfile);
            $pubkey = $x509->getPublicKey();

            $rsa = new Crypt_RSA();
            $rsa->loadKey($pubkey); // public key
            $rsa->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1);

            $verifyResult = $rsa->verify($bufSignSrc, base64_decode(trim($signMsg)));


            $verify_Result = null;
            $pay_Result = null;
            if ($verifyResult) {
                $verify_Result = "报文验签成功!";
                if ($payResult == 1) {
                    $pay_Result = "订单支付成功!";
                } else {
                    $pay_Result = "订单支付失败!";
                }
            } else {
                $verify_Result = "报文验签失败!";
                $pay_Result = "因报文验签失败，订单支付失败!";
            }
        }


//signType 0 验签
        $this->pay_result = false;
        if ($payResult == 1) {
            $pay_Result_0 = "订单支付成功！";
            $this->pay_result = true;
            return true;
        } else {
            $pay_Result_0 = "订单支付失败！";
        }

        if ($signMsg == strtoupper(md5($bufSignSrc . "&key=" . $md5key))) {
            $verify_Result_0 = "报文验签成功!";
        } else {
            $verify_Result_0 = "报文验签失败!";
        }
        return false;
    }

    function return_verify(){
        return $this->notify_verify();
    }

    public function getPayResult($parms){
        return $this->pay_result;
    }
}